import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.zip.Inflater;

/**
 * 最终解密测试 - 使用正确的密钥
 */
public class FinalDecryptionTest {
    
    // 从ep解密得到的AES密钥
    private static final String AES_KEY_HEX = "d18b48d47c664dc697ae620dc463ac556ce657ce57f45bc4e46177ad751db597";
    
    // data字段（Base64）
    private static final String DATA_BASE64 = "wHBy2LDIay6WCgEybO8bw/5OxmVd4N++OJpwr/Tgjw+TA8iZ4HAy4bN8UWtwmeGz+dqU/zX6myCireq+q465rqUqpXLhma2aEPqTaNvUTv/Y71kVpkMBkgrjMnVkIi/iBV5eKsrTPfLWO8bt0mSbLM8ghswC2m2YRInkqWXHrc8Nw0JsNjwCllOUdtwe3NuIx8oQuQ2fqj1G3g3xMp6B4sWBNAo+SjTNuKnS4chvbaD3RYnGvSLyNYu+sqbKeRNofCwVn0lVrjCAGtC9d5nqhFiGw0vWksPfmCRn7vRsl7LnqcXb+Fal/hhREBsaRJdMrst3vOEeQI6pt3RGKZ3VOsliNziKbLiNnXp2zY2fin32okAFwIOczPgeQA1yAM4FCnuT9FYAMn5ecAOY7WFhJPcOqVThy0giCJrBzpIzEHXTin+BWBO1PR8wMzBqpf6us9mhBZGzu40mzVN34xXK646aMr8f2DcD9yGO20v5icEz3OUcAeayMq+YKmBoypmvQUnaGa8pjr7RfvvajY+7pu6QHqRAQ3NLY1KjIoT3PKjabb7owQ1Txw5+Ajfjen7VEeF/Dq03nPMtNOpqD3tCdWDHWir+akJcEPtPzK4Bo2K3FrLBZt2igZD6/04jtwoAojHibKqUM1Rj5h2iijH65eAU1XKTpqDPNtcP5lwa1bFNV+GvuzHM+N4gcoxiELhQeG7xiUcsZrJvadkDO2z+If9vLkXTSdMKrqozUjLRapyXpULcVL8negHnj+2vKZVdoGiDhXlm23XDFjLY91ZqX2eGfGNmpJxftl83N6q4dyXpzD2gR/chHfm0CukVlL8P8aPAfEDcAsyQETc5oVLzetGVSkGBbQl+axZu8U2Ap9CXaTi1b2VcI3he19nvgG8XEFnwP6Tbicm5PDDsiRjo2MRqfuPLWkcSHTmBlS6w8yrzAvth9x/bBLg8XLs8M/B/dKSfOa9sbptfTMmEuuhWbnqCyqnFSUt8lsFlcUbJdK02TcMbd789pANnrKTTfFeOUehu5XReHng4DfV7f6boQmJPnZfwuR8qFwp7vwme235RTloktlkQu/2QFl2LmCv+/8Za43dEdFba9Ae6I1p+50zunyIjGTE6/9RT+g/zgagzgV/qDDSM5VF6E2Ic62W/KkpfSPMHAk5Jwg0LlsSMnFXYCynZoDZ5M8s62V15VaEII3s/6wPCu4lba/BxPanRtw60EVsvrJ7B0mnG+hcW8AGVeG1ZBIhgPH887/bY+05b0MnSkhjlrys8GKSaukVbtnrLJmjePt+LdLe6tH2NTwxjbHhJR028ZWaQKvdC5BD2hRflDMBPKL68D6YJ2bitqnKKdEqYHdCMXtOXh68XUqwfkoF3phQtYHyrqF4Wsgukf3/gAlt/yF0dXFTIUzoDTc34MEAaLFENVFDt4PUnYw2SRT8i/bhi3tcavu6Hnjs=";
    
    public static void main(String[] args) {
        try {
            System.out.println("=" + "=".repeat(99));
            System.out.println("最终解密测试");
            System.out.println("=" + "=".repeat(99));
            
            // 将hex密钥转换为字节数组
            byte[] aesKey = hexToBytes(AES_KEY_HEX);
            System.out.println("\nAES密钥 (32字节):");
            System.out.println(bytesToHex(aesKey));
            
            // Base64解码data
            byte[] dataWithIV = Base64.getDecoder().decode(DATA_BASE64);
            System.out.println("\ndata解码后长度: " + dataWithIV.length + " 字节");
            
            // 提取IV（前16字节）
            byte[] iv = Arrays.copyOfRange(dataWithIV, 0, 16);
            System.out.println("\nIV (16字节):");
            System.out.println(bytesToHex(iv));
            
            // 提取加密数据（16字节之后）
            byte[] encrypted = Arrays.copyOfRange(dataWithIV, 16, dataWithIV.length);
            System.out.println("\n加密数据长度: " + encrypted.length + " 字节");
            
            // AES解密
            System.out.println("\n" + "=".repeat(100));
            System.out.println("尝试AES-256-CBC解密...");
            System.out.println("=".repeat(100));
            
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            
            byte[] decrypted = cipher.doFinal(encrypted);
            System.out.println("✅ AES解密成功！");
            System.out.println("解密后长度: " + decrypted.length + " 字节");
            System.out.println("解密后数据(hex前64字节): " + bytesToHex(Arrays.copyOf(decrypted, Math.min(64, decrypted.length))));
            
            // zlib解压
            System.out.println("\n" + "=".repeat(100));
            System.out.println("尝试zlib解压...");
            System.out.println("=".repeat(100));
            
            Inflater inflater = new Inflater(true); // true = RAW deflate (wbits=-15)
            inflater.setInput(decrypted);
            
            byte[] decompressed = new byte[1024 * 100]; // 100KB buffer
            int decompressedLength = inflater.inflate(decompressed);
            inflater.end();
            
            System.out.println("✅ zlib解压成功！");
            System.out.println("解压后长度: " + decompressedLength + " 字节");
            
            String json = new String(decompressed, 0, decompressedLength, StandardCharsets.UTF_8);
            System.out.println("\n" + "=".repeat(100));
            System.out.println("解密后的JSON数据:");
            System.out.println("=".repeat(100));
            System.out.println(json);
            
        } catch (Exception e) {
            System.out.println("❌ 错误: " + e.getClass().getSimpleName() + " - " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private static byte[] hexToBytes(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                                 + Character.digit(hex.charAt(i+1), 16));
        }
        return data;
    }
    
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}


